package com.cskaoyan.market.controller.wx;

import com.cskaoyan.market.annotation.ValidParam;
import com.cskaoyan.market.db.domain.MarketUser;
import com.cskaoyan.market.service.wx.WxAuthService;
import com.cskaoyan.market.service.wx.CloudService;
import com.cskaoyan.market.shiro.CskaoyanToken;
import com.cskaoyan.market.util.ResponseUtil;
import com.cskaoyan.market.vo.wx.lhh.RegisterUserVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @ClassName WxAuthController
 * @Description /wx/auth/login
 * 用户登陆与登出页面
 * @Author MZ
 * @Date 2023/5/19 17:29
 */
@RestController
@RequestMapping("wx/auth")
public class WxAuthController {

    private static String VEYIFY_CODE;

    @Autowired
    SecurityManager securityManager;
    @Autowired
    WxAuthService wxAuthService;
    @Autowired
    CloudService cloudService;

    /**
     * @MethodName register
     * @Description 注册用户
     * @param: user
     * @param: bindingResult
     * @return: java.lang.Object
     * @Author MZ
     * @Date 9:11 2023/5/23
     **/
    @ValidParam
    @PostMapping("register")
    public Object register(@RequestBody @Valid RegisterUserVo user, BindingResult bindingResult) {

        String username = user.getUsername();
        String password = user.getPassword();

        String userCode = user.getCode();
        if (!userCode.equals(VEYIFY_CODE)) {
            return ResponseUtil.codeFail();
        }

        String mobile = user.getMobile();
        Integer row = wxAuthService.registerUser(username, password, mobile);

        if (row == 0) {
            return ResponseUtil.badArgumentValue();
        }
        if (row == -1) {
            return ResponseUtil.registerUsernameRepeat();
        }
        Map<String, String> map = new HashMap<>();
        map.put("username", username);
        map.put("password", password);

        return login(map);
    }

    /**
     * @MethodName regCaptcha
     * @Description 发送验证码
     * @param: map
     * @return: java.lang.Object
     * @Author MZ
     * @Date 9:10 2023/5/23
     **/
    @PostMapping("regCaptcha")
    public Object regCaptcha(@RequestBody Map<String, String> map) {
        String mobile = map.get("mobile");
        Random random = new Random();
        String code = String.valueOf(random.nextInt(9));
        for (int i = 0; i < 3; i++) {
            code += random.nextInt(9);
        }
        VEYIFY_CODE = code;
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("code", code);
        cloudService.sendSms(mobile, code);

        return ResponseUtil.ok();
    }


    /**
     * @MethodName login
     * @Description 登陆
     * @param: map
     * @return: java.lang.Object
     * @Author MZ
     * @Date 9:11 2023/5/23
     **/
    @PostMapping("login")
    public Object login(@RequestBody Map<String, String> map) {
        String username = map.get("username");
        String password = map.get("password");
        // 进行认证操作
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        // 传入参数
        CskaoyanToken token = new CskaoyanToken(username,password,"wx");
        try {
            subject.login(token);
            System.out.println("登陆成功！");
        } catch (Exception e) {
            System.out.println("登陆失败，用户名密码错误");
            // {"errno":700,"errmsg":"账号不存在"}
            return ResponseUtil.loginFail();
        }
        // 认证通过，登陆成功
        MarketUser user = wxAuthService.getUserByUsername(username);
        // 放入session
        Integer id = user.getId();
        Session session = subject.getSession();
        session.setAttribute("username", username);
        session.setAttribute("userId", id);

        Map<String, Object> result = new HashMap<>();
        Map<String, String> userInfoMap = new HashMap<>();
        userInfoMap.put("nickName", user.getNickname());
        userInfoMap.put("avatarUrl", user.getAvatar());

        result.put("userInfo", userInfoMap);
        result.put("token", session.getId());

        return ResponseUtil.ok(result);
    }

    // 登出
    @PostMapping("logout")
    public Object logout(@RequestBody Map<String, String> map) {
        String username = map.get("username");
        String password = map.get("password");
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        token.clear();
        return ResponseUtil.ok();
    }

    @PostMapping("reset")
    public Object reset(@RequestBody Map<String, String> map) {
        // {"mobile":"12121212","code":"5555","password":"666666"}
        String mobile = map.get("mobile");
        String code = map.get("code");
        String password = map.get("password");

        if (!code.equals(VEYIFY_CODE)) {
            return ResponseUtil.codeFail();
        }
        int row = wxAuthService.reset(mobile, password);
        if (row != 1) {
            return ResponseUtil.badArgument();
        }
        return ResponseUtil.ok();
    }

}
